package com.zhny.utils.database.book;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

/**
 * 课本上填了静态代码块和properties文件的数据库链接方法
 */
public class DbConnection {
	private static String driverName; 
	private static String userName;   //创建时的用户名                
	private static String password;  //数据库的密码   
	private static String url1;
	private static String url2;
	private static String url3;
	private static String url;
	
	static {
		Properties properties = new Properties();
		try {
			properties.load(DbConnection.class.getClassLoader().getResourceAsStream("db.properties"));
			driverName = properties.getProperty("drivername");
			userName = properties.getProperty("username");
			password = properties.getProperty("password");
			url1 = properties.getProperty("url");
			url2="?user="+userName+"&password="+password;
			 url3="&userUnicode=true&characterEncoding=utf8";
			 url=url1+url2+url3;
		} catch (Exception e) {
			//TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static Connection getConnect(){
		try {
			Class.forName(driverName);
			Connection con = DriverManager.getConnection(url);
			return con; 
		}	
		catch(Exception ex){
		    ex.printStackTrace();  
		}finally{		    	
		}
		return null;
	  }
	
	public static void closeDb(ResultSet rs,PreparedStatement ps,Connection con) {
		try{		 
			if(rs!=null)			
				rs.close();
			if(ps!=null)
				ps.close();
			if(con!=null)	
				con.close();
		}catch(Exception ex){
			ex.printStackTrace();  
		} 
	}
}
